package com.ddpyjqtd.singleton;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * @Description: 暴力破解测试 反射一次相当于new一次对象，反序列化的过程相关于new一次对象
 * @author: ddpyjqtd
 * @Date: 2019年3月9日
 *
 */
public class DestoryTest {

	public static void main(String[] args) throws Exception {
		// 反射，相当于两次new
		 reflectFunction();

		// 序列化再反序列化，反序列化的过程也相当于两次new
//		serializationFunction();
	}

	/**
	 * @Description: 序列化再反序列化，反序列化的过程也相当于两次new
	 * 
	 * @author: ddpyjqtd
	 * @Date: 2019年3月10日
	 *
	 * @throws Exception
	 */
	public static void serializationFunction() throws Exception {
		HungrySingleton hungrySingleton = HungrySingleton.getInstance();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(hungrySingleton);
		oos.flush();
		oos.close();
		bos.close();

		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		HungrySingleton hungrySingleton2 = (HungrySingleton) ois.readObject();
		ois.close();
		bis.close();
		System.out.println(hungrySingleton + ".." + hungrySingleton2);
	}

	public static void reflectFunction() throws Exception {
		Class<?> clazz = StaticInnerClass.class;
		Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
		Constructor<?> declaredConstructors = declaredConstructor;
		declaredConstructors.setAccessible(true);
		Object newInstance = declaredConstructors.newInstance();
		Object newInstance2 = declaredConstructors.newInstance();// 相当于new 了两次对象
		System.err.println(newInstance + "..." + newInstance2);
	}

}
